<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Requests\System\Role\StoreRequest;
use App\Http\Requests\System\Role\UpdateRequest;
use App\Http\Resources\System\Role\IndexResource;
use App\Http\Resources\System\Role\InfoResource;
use App\Models\System\Admin;
use App\Models\System\Role;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\QueryBuilder\QueryBuilder;

class RoleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        /** @var Admin $user */
        $user = $request->user();
        $query = $user->is_super_admin ? Role::query() : $user->roles();
        $list = QueryBuilder::for($query, $request)
            ->allowedFilters(['id', 'title', 'status', 'code', 'sort'])
            ->allowedSorts('sort')
            ->paginate();

        return $this->success(IndexResource::collection($list));
    }

    public function show(Role $role): JsonResponse
    {
        return $this->success(new InfoResource($role));
    }

    public function store(StoreRequest $request): JsonResponse
    {
        $data = $request->validated();
        $row = new Role($data);

        DB::transaction(function () use ($row, $request, $data) {
            $row->save();
            /** @var Admin $user */
            $user = $request->user();
            $row->menus()->attach($user->getMenusIds()->intersect($data['menus']));
        });

        return $this->success([
            'id' => $row->id,
        ], '添加成功');
    }

    public function update(Role $role, UpdateRequest $request): JsonResponse
    {
        $data = $request->validated();
        $role->fill($data);

        DB::transaction(function () use ($role, $request, $data) {
            $role->save();
            /** @var Admin $user */
            $user = $request->user();
            $role->menus()->sync($user->getMenusIds()->intersect($data['menus']));
        });

        return $this->success([], '更新成功');
    }

    public function destroy(Role $role): JsonResponse
    {
        $role->delete();

        return $this->success([], '删除成功');
    }
}
